#include "types.h"
#include "board.h"
#include "global.h"
#include "mcu.h"
#include "detect.h"
#include "menu.h"
#include "ms_reg.h"
#include "power.h"
#include "debug.h"
#include "Common.h"
#include "ms_rwreg.h"
#include "msosd.h"
#include "misc.h"
#include "NVRam.h"
#include "mstar.h"
#include "UserPref.h"
#include "keypad.h"
//#include "Panel.h"
#include "msflash.h"  //2006-03-20
#include "ddc2bi.h"
#include "gpio_def.h"
#if ENABLE_RTE
#include "drvmsovd.h"
#endif
#if ENABLE_DP_INPUT
#include "drvDPRxApp.h"
#endif

#if (MS_PM)
#include "Ms_PM.h"
#endif
#if DDCCI_ENABLE||AudioFunc
#include "adjust.h"
#endif
#include "MsDLC.h"
#include "MsACE.h"

#if ENABLE_HDMI
#include "MsHDMI.h"
#if ENABLE_CEC
#include "apiCEC.h"
#endif
#endif
#if ENABLE_EDP_OUTPUT
#include "DPTxApp.h"
#endif

#if MS_DAC
#include "drvDAC.h"
#endif

#if ENABLE_LED_CONTROLLER
#include "LEDControl.h"
#endif

////////////////////////////////////
//#include "drvMcu.h"
///////////////////////////////////

#if ENABLE_DPS
#include "msDPS_Handler.h"
#include "userprefdef.h"
#include "msdps_setting.h"
#endif
#if ENABLE_DSC
#include "msDSC_Handler.h"
//#include "userprefdef.h"
#include "msdsc_setting.h"
#endif

#define Main_DEBUG    1
#if ENABLE_DEBUG&&Main_DEBUG
    #define Main_printData(str, value)   printData(str, value)
    #define Main_printMsg(str)           printMsg(str)
#else
    #define Main_printData(str, value)
    #define Main_printMsg(str)
#endif

void Init_Device( void );
void Main_SlowTimerHandler(void);

extern void Init_GlobalVariables( void );
extern void i2C_Intial( void ); //2006/03/20
#if ENABLE_HDCP&&HDCPKEY_IN_Flash
extern void msInitHDCPProductionKey( void );
#endif
extern Bool ResetAllSetting( void );

extern BYTE xdata PowerDownCounter;

BYTE xdata mainloop = 0;

typedef unsigned int  __u16;    // 2 bytes
typedef unsigned char   __u8;     // 1 byte

#ifndef U8
#define U8    BYTE
#endif

#ifndef BOOLEAN
#define BOOLEAN    BYTE
#endif
//extern __u8*  MDrv_Get_HID_Report_Raw_Data(void);
//extern U8 drvUSBHost_HID_Initial(void);
extern U8 drvUSBHost_HID_Initial_Port2(U8 u8Interface);
extern void MDrv_USB_Init(DWORD USBAdr);
extern void MDrv_USB_Init_Port2(DWORD USBAdr);
extern BOOLEAN  MDrv_Usb_Device_Enum(void);
extern BOOLEAN  MDrv_Usb_Device_Enum_Port2(void);
extern BOOLEAN MDrv_UsbDeviceConnect(void);
extern BOOLEAN MDrv_UsbDeviceConnect_Port2(void);
extern void drvUSBHost_UTMIInitial();
extern void  MDrv_Get_Keyboard_Staus(U8 u8Interface);
extern void  MDrv_Get_Mouse_Staus(U8 u8Interface);
extern void  MDrv_Get_Mouse_Staus_Port2(U8 u8Interface);
extern void  MDrv_Get_Keyboard_Staus_Port2(U8 u8Interface);
#define PORT
#define PORT2
#define HOST20_INTERFACE_NUM_MAX    5
extern U8 xdata PORT_DEVICE[HOST20_INTERFACE_NUM_MAX];//support 5 interface
extern U8 xdata PORT2_DEVICE[HOST20_INTERFACE_NUM_MAX];

BYTE code msMainNullData[] = {0};
void msMainDummy(void)
{
    BYTE xdata i = msMainNullData[0];
}

void main( void )
{
    BYTE UsbConnect = 0, UsbConnect_Port2 = 0;

#if (CHIP_ID == CHIP_TSUM9 ||CHIP_ID == CHIP_TSUMF)
    drvmStar_PowerOnInit();
#if (CHIP_ID == CHIP_TSUMF)
    MPLL_CLOCK_ADC(TRUE);
#endif
#else
    #if (MS_PM)
    msPM_Exit();    // for WDT reset in PM mode
    #endif
#endif

#if ENABLE_DP_INPUT
    g_bDoDPInit = TRUE;
#endif
    Init_MCU();

#if (CHIP_ID == CHIP_TSUM9||CHIP_ID == CHIP_TSUMF)
	if (!g_bFROTrimResult)
		Main_printMsg("FRO trim failed!");
#endif

#if( ENABLE_WATCH_DOG )
    WDT_CLEAR();
#endif

    ScalerReset();
    mcuSetSystemSpeed(SPEED_NORMAL_MODE);
    ForceDelay1ms( 100 );
    g_ucFlashID = ReadFlashID();

#if !USEFLASH
    i2C_Intial();
#endif

    ReadMonitorSetting();
    mStar_Init();
    mStar_ACOnInit();
#if  (MS_PM)
    msPM_Init();
#endif
    CheckFactoryKeyStatus();
    Init_GlobalVariables();
    Menu_InitVariable();
    Init_Device();
    DDC2Bi_Init();

    Main_printData("  g_u8SystemSpeedMode:%d", g_u8SystemSpeedMode);
	
#if ENABLE_USB_INPUT
#ifdef PORT
    MDrv_USB_Init(HK_USB_XDATA_ADDR);
#endif
#ifdef PORT2
    MDrv_USB_Init_Port2(HK_USB_XDATA_ADDR_PORT2);
#endif
#endif

    while( 1 )
    {
#if (MS_PM)
        msPM_Handler();
        if(!msPM_IsState_IDLE())
            continue;
#endif

        Main_SlowTimerHandler();

        DebugHandler();

#if( ENABLE_WATCH_DOG )
        WDT_CLEAR();
#endif

#if ENABLE_DEBUG
        if( DebugOnlyFlag )
            continue;
#endif

        DDC2Bi_CommandHandler();

#if ENABLE_HDCP&&HDCPKEY_IN_Flash
        if( WriteHDCPcodeFlag )
            continue;
#endif

#if ENABLE_HDCP&&HDCPKEY_IN_Flash
        if( LoadHDCPKeyFlag )
        {
            msInitHDCPProductionKey();
            Clr_LoadHDCPKeyFlag();
        }
#endif

#if ENABLE_LED_CONTROLLER
        msLED_Hander();
#endif

#if ENABLE_DP_INPUT
        DPRxHandle();             // DP hander
#endif

        Power_PowerHandler();
#if (MS_PM)
        if(!msPM_IsState_IDLE())
            continue;
#endif

        if( !ModeDetectCounter || InputTimingChangeFlag )
        {
            mStar_MonitorInputTiming();
            ModeDetectCounter = 20;
        }

        mStar_ModeHandler();

#if (ENABLE_HDMI || ENABLE_DVI)
#if(CHIP_ID==CHIP_TSUM9)
        drv_TMDS_DATA_ALIGN();
#endif
#endif

#if ENABLE_HDMI
        mstar_HDMIHandler();
#if ENABLE_CEC
        api_CEC_Handler();
#endif
#endif
/*wz 2017.08.01 zoro add*/
#if AUTOCHAGE_HDMI2DP
	AutoChange_display_mode();
#endif

#if ENABLE_DPS
        if(bRunToolFlag)
            continue;
        //printMsg( "msDPS_Handler" );
        msDPS_Handler();
#endif
#if ENABLE_DSC
#if !DEBUG_DSC_withoutInterrupt
        //printMsg( "msDSC_Handler" );
        msDSC_Handler();
        //ForceDelay1ms(1000);
#endif
#endif
#if ENABLE_DLC
        msDlcHandler();
#endif

#if AudioFunc
#if ((CHIP_ID==CHIP_TSUMC || CHIP_ID==CHIP_TSUMD || CHIP_ID==CHIP_TSUM9|| CHIP_ID==CHIP_TSUMF) && MS_DAC)
        msDACInitStep();
#endif
#if (MS_DAC)
        msAudioGainToggle();
#endif
#endif

        Menu_OsdHandler();
#if ENABLE_EDP_OUTPUT
		//if( !SyncLossState() )
		DPTxHandle();
#endif

#if (MS_PM)
        if(!msPM_IsState_IDLE())
            continue;
#endif

#if MWEFunction
        if(( ColorAutoDetectFlag || UserPrefDcrMode ) && PowerOnFlag && !SyncLossState() && InputTimingStableFlag && ( !DisplayLogoFlag ) )
#else
        if(( UserPrefDcrMode ) && PowerOnFlag && !SyncLossState() && InputTimingStableFlag && ( !DisplayLogoFlag ) )
#endif
        {
            msDlcHandler();
            msDCRHandler();
        }

#if ENABLE_MHL
#if(MHL_HW_RTERM_SUPPORT)
        mapi_mhl_RtermControlHWMode(FALSE);
#endif

        mapi_mhl_handler();

#if(MHL_HW_RTERM_SUPPORT)
        mapi_mhl_RtermControlHWMode(TRUE);
#endif
#endif

#if ENABLE_TOUCH_PANEL||ENABLE_TOUCH_PANEL_CTRL_OSD
        TouchPanelHandler();
#endif

#if USEFLASH
        UserPref_FlashDataSaving();
#endif
#if ENABLE_USB_INPUT
#ifdef PORT
        if (MDrv_UsbDeviceConnect()==1)
        {
            if (UsbConnect == 0)  // do usb device enumeration
            {
                Main_printMsg("USB device plug-in!!\n");
                if (MDrv_Usb_Device_Enum() == 1)
                {
                    UsbConnect = 1;
                    Main_printMsg("1111 USB enumeration success!!\n");
                }
                else
                    Main_printMsg("1111 USB enumeration fail!!\n");
            }
            else    // polling usb device input data, ex. move mouse, press buttoms
            {
                U8 i;
                for(i=0;i<HOST20_INTERFACE_NUM_MAX;i++)
                {
                    if(PORT_DEVICE[i]==1)  //Keyboard
                        MDrv_Get_Keyboard_Staus(i);
                    else if(PORT_DEVICE[i]==2) //Mouse
                        MDrv_Get_Mouse_Staus(i);
                }
            }
        }
        else
        {
            if (UsbConnect == 1)
                Main_printMsg("USB device plug-out!!\n");
            UsbConnect = 0;
        }
#endif
#ifdef PORT2
        if (MDrv_UsbDeviceConnect_Port2()==1)
        {
            if (UsbConnect_Port2 == 0)  // do usb device enumeration
            {
                Main_printMsg("USB device plug-in!!\n");
                if (MDrv_Usb_Device_Enum_Port2() == 1)
                {
                    UsbConnect_Port2 = 1;
                    Main_printMsg("2222 USB enumeration success!!\n");
    }
                else
                    Main_printMsg("2222 USB enumeration fail!!\n");
            }
            else    // polling usb device input data, ex. move mouse, press buttoms
            {
                U8 j;
                for(j=0;j<HOST20_INTERFACE_NUM_MAX;j++)
                {
                    if(PORT2_DEVICE[j]==1)  //Keyboard
                        MDrv_Get_Keyboard_Staus_Port2(j);
                    else if(PORT2_DEVICE[j]==2) //Mouse
                        MDrv_Get_Mouse_Staus_Port2(j);
                }
            }
        }
        else
        {
            if (UsbConnect_Port2 == 1)
                Main_printMsg("USB device plug-out!!\n");
            UsbConnect_Port2 = 0;
        }
#endif
#endif
    }

}

void Init_Device()
{
#if ENABLE_USB_INPUT
    hw_USB_HI();
#endif

#if ENABLE_TOUCH_KEY
    TouchKeyRestortCounter = TouchKey_Init();
#endif

#if AudioFunc
    mStar_AdjustVolume( 0 );
#endif

#if ENABLE_TOUCH_PANEL||ENABLE_TOUCH_PANEL_CTRL_OSD
    TPL_InitSetting();
#endif

    if( PowerOnFlag )
    {
        Power_TurnOnGreenLed();
    }
    else
    {
        Power_TurnOffLed();
    }
}

void Main_SlowTimerHandler(void)
{
    if(ms10Flag)
    {
        if(ModeDetectCounter)
        {
            if(ModeDetectCounter > 10)
                ModeDetectCounter -= 10;
            else
                ModeDetectCounter = 0;
        }

        if(TPDebunceCounter)
        {
            if(TPDebunceCounter > 10)
            {
                TPDebunceCounter -= 10;
            }
            else
            {
                TPDebunceCounter = 0;
                Set_StartScanKeyFlag();
            }
        }

#if ENABLE_HDMI
        if(HdmiPollingCounter)
        {
            if( HdmiPollingCounter > 10)
                HdmiPollingCounter -= 10;
            else
                HdmiPollingCounter = 0;
        }

        if( gScInfo.InputTmdsType == TMDS_HDMI && ( !( SrcFlags&( SyncLoss | bUnsupportMode ) ) ) )
        {
            if( gScInfo.wAviPktLossCnt < AviPktLossBound )
                gScInfo.wAviPktLossCnt += 10;
        }
#endif

        if(!FreeRunModeFlag)
        {
#if ENABLE_TOUCH_PANEL || ENABLE_TOUCH_PANEL_CTRL_OSD
            if(TPL_PollingCounter)
            {
                if(TPL_PollingCounter > 10)
                    TPL_PollingCounter -= 10;
                else
                    TPL_PollingCounter = 0;
            }
#endif
        }

#if ENABLE_MHL
    #if ((CHIP_ID == CHIP_TSUMC) || (CHIP_ID == CHIP_TSUMD) || (CHIP_ID == CHIP_TSUM9)|| (CHIP_ID == CHIP_TSUMF))
        mapi_mhl_PollingTimerhandler();
    #endif
#endif

#if MS_DAC && ((CHIP_ID == CHIP_TSUMC) || (CHIP_ID == CHIP_TSUMD) || (CHIP_ID == CHIP_TSUM9)|| (CHIP_ID == CHIP_TSUMF))
#if (!InitialDACByISR)
    if( w16DAC_DePopCounter )
    {
        if(w16DAC_DePopCounter > 10)
        {
            w16DAC_DePopCounter -= 10;
        }
        else
        {
            w16DAC_DePopCounter = 0;
            bDAC_DePopFlag = 1;
        }
    }
#endif
#endif

    #if ENABLE_LED_CONTROLLER
        LEDProcess_10mS();
    #endif

        Clr_ms10Flag();
    }

    if(ms50Flag)
    {
#if 0//MS_DAC && (CHIP_ID==CHIP_TSUMC ||CHIP_ID==CHIP_TSUMD)
#if CheckInitialDACTime
    Main_printData("w16DAC_DePopStep==%d",w16DAC_DePopStep);
    Main_printData("w16DAC_DePopCounter==%d",w16DAC_DePopCounter);

    //TIME_MEASURE_END();
#endif
#endif

#if MS_DAC
        if( ToggleGainCntr )
        {
            if(ToggleGainCntr > 50)
                ToggleGainCntr -= 50;
            else
            {
                ToggleGainCntr = 0;
                bToggleGainFlag = 1;
            }
        }
#endif

#if ENABLE_TOUCH_KEY
        if(TouchKeyRestortCounter)
        {
            TouchKeyRestortCounter--;
            if(!TouchKeyRestortCounter && (TouchKey_InitStatus() == PRE_RESTORT))
                TouchKey_Restort_Reg();

        }

#if ENABLE_LOW_CONTACT
        if(TouchKeyLowContactDelay)
        {
            TouchKeyLowContactDelay--;
            if(!TouchKeyLowContactDelay && (TouchKey_InitStatus() == PRE_RESTORT))
            {
                TouchKey_Restort_Reg();
                TouchKeyLowContactDetectCntr = 0;
            }
        }
#endif

#if TOUCH_KEY_POWER_KEY_DEBOUNCE
        if( bPowerKeyPressed )
        {
            if( PowerKeyDebounceCntr < POWER_KEY_DEBOUNCE_PEROID )
                PowerKeyDebounceCntr++;
        }
#endif
#endif

        Clr_ms50Flag();
    }

    if(SecondFlag)
    {
    #if ENABLE_DEBUG && 0
        if(Second%1 == 0)
        {
        #if  ENABLE_WATCH_DOG_INT
            BYTE  final_status;                 // use idata to speedup
            final_status = msRegs[REG_2B10];
            msRegs[REG_2B08]=0x00;
            if( final_status & _BIT1 )
                Main_printMsg("WDT interrupt");

            Main_printData("u8WDT_Status==%x",u8WDT_Status);
            //u8WDT_Status=0;
        #endif
        }
        if(Second%5 == 0)
         Main_printData("Second==%d",Second);
    #endif
        Second++;

#if USEFLASH
        UserPref_FlashSaveFlagCheck();
#endif

#if  ENABLE_LED_CONTROLLER
        LEDProcess_1S();
#endif

        if( PowerOnFlag && !PowerSavingFlag )
        {
            if( BlacklitTime < 0xFFFFFFFFul )
            {
                BlacklitTime += 1;
            }
            else
                BlacklitTime = 0;

            if( BlacklitTime > 0 && ( BlacklitTime % 1800 ) == 0 )
                SaveBlacklitTimeFlag = 1;
        }

        if( OsdCounter )
        {
            if( --OsdCounter == 0 )
            {
                Set_OsdTimeoutFlag();
            }
        }

#if HotInputSelect
        if( HotKeyCounter )
        {
            if( --HotKeyCounter == 0 )
            {
                if( PressExitFlag )
                    Set_EnableShowAutoFlag();
            }
        }
#endif

        if( PowerDownCounter )
        {
            if( --PowerDownCounter == 0 )
            {
                Set_ForcePowerSavingFlag();
            }
        }
        Set_ChangePatternFlag();

		if (g_SwitchSec && g_CountSwitchPortTimeFlag)
		{
            if( --g_SwitchSec == 0 )
            {
                g_CountSwitchPortTimeFlag=FALSE;
				g_SwitchSec=DEF_FORCE_DPMS;
                Set_ForcePowerSavingFlag();
            }
		}

#if ENABLE_TOUCH_KEY

#if ENABLE_LOW_CONTACT
        if(TouchKeyLowContactDetectCntr)
            TouchKeyLowContactDetectCntr--;
#endif

        if((Second%2) == 0)
        {
            if(!TouchKeyRestortCounter) // 120417 coding addition
                TouchKeyRestortCounter = TouchKey_Check_ESD();
        }
#endif
        Clr_SecondFlag();
    }

    if( SaveBlacklitTimeFlag )
    {
        SaveBlacklitTimeFlag = 0;
#if USEFLASH
        UserprefBacklighttime = BlacklitTime;
        UserPref_EnableFlashSaveBit( bFlashForceSaveMonitor2Bit );
#else
        SaveBlacklitTime();
#endif
    }

#if 0//ENABLE_TOUCH_KEY
#if TOUCH_KEY_CTRL_LED
    if(TouchKey_GetLEDStatus() != TouchKeySetLEDStatus)
        TouchKey_CtrlLED(TouchKeySetLEDStatus);
#endif
#endif

}
